package com.example.experiment_6;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {

    private final List<Contact> contacts;

    public ContactAdapter(List<Contact> contacts) { this.contacts = contacts; }

    public static class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView txtName;
        private final TextView txtPhone;

        public ContactViewHolder(View itemView) {
            super(itemView);
            txtName = itemView.findViewById(R.id.txt_name);
            txtPhone = itemView.findViewById(R.id.txt_phone);
        }

        public void bindContact(Contact contact) {
            txtName.setText(contact.getName());
            txtPhone.setText(contact.getPhone());
        }
    }

    @NonNull
    @Override
    public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_item, parent, false);
        ContactViewHolder contactViewHolder = new ContactViewHolder(view);

        // 对于列表中每一项的点击事件的实现
        contactViewHolder.itemView.setOnClickListener(itemView -> {
            int position = contactViewHolder.getAdapterPosition();
            Contact contact = contacts.get(position);
            Toast.makeText(itemView.getContext(), contact.getName(), Toast.LENGTH_SHORT).show();
        });
        return contactViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
        Contact contact = contacts.get(position);
        holder.bindContact(contact);
    }

    @Override
    public int getItemCount() { return contacts.size(); }

}
